﻿using System;
using System.Web.Mvc;
using Account.IService.Entry;
using System.Configuration;
using Framework.Common.Event;
using Framework.MVC;
using System.Web;
using FrontCenter.Models;

namespace FrontCenter.Controllers
{
    public class UserController : AsyncControllerBase
    {
        #region Field

        private readonly static string m_identity_error = ConfigurationManager.AppSettings["IdentityErrorPage"];
        private const string m_user_resource = "u000";
        private const char m_split = ';';
        private const string m_resource = "verifycode";

        private readonly static int m_old = int.Parse(ConfigurationManager.AppSettings["Old"]);

        #endregion Field

        #region Temp

        private static readonly System.Text.RegularExpressions.Regex m_name = new System.Text.RegularExpressions.Regex(@"^[\u4e00-\u9fa5]{2,15}$", System.Text.RegularExpressions.RegexOptions.Compiled);
        private static readonly System.Text.RegularExpressions.Regex m_email = new System.Text.RegularExpressions.Regex(@"^(\w(\.\w)?){1,64}@(\w(\.\w)?){1,255}$", System.Text.RegularExpressions.RegexOptions.Compiled);
        private const string m_address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; //包含的地址信息
        private static readonly string[] m_code = new string[] { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }; //校验数
        private static readonly int[] m_wi = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; //权值数组
        private static readonly System.Text.RegularExpressions.Regex m_date = new System.Text.RegularExpressions.Regex(@"^(?:(?!0000)[0-9]{4}([-/.]?)(?:(?:0?[1-9]|1[0-2])([-/.]?)(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])([-/.]?)(?:29|30)|(?:0?[13578]|1[02])([-/.]?)31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2([-/.]?)29)?$", System.Text.RegularExpressions.RegexOptions.Compiled);

        private bool IsIDCard(string data)
        {
            if (data == null)
                return false;

            Int64 n;
            if (data.Length == 18)
            {
                if (!Int64.TryParse(data.Remove(17), out n) || n < Math.Pow(10, 16) || !Int64.TryParse(data.Replace('x', '0').Replace('X', '0'), out n))
                    return false;//数字验证
                if (m_address.IndexOf(data.Remove(2)) == -1)
                    return false;//省份验证

                string birth = data.Substring(6, 8).Insert(6, "-").Insert(4, "-");

                if (!m_date.IsMatch(birth))
                    return false;//生日验证

                char[] Ai = data.Remove(17).ToCharArray();

                int sum = 0;

                for (int i = 0; i < 17; i++)
                    sum += m_wi[i] * int.Parse(Ai[i].ToString());

                int y;

                Math.DivRem(sum, 11, out y);

                if (String.Compare(m_code[y], data.Substring(17, 1), StringComparison.OrdinalIgnoreCase) != 0)
                    return false;//校验码验证

                return true;//符合GB11643-1999标准
            }
            else if (data.Length == 15)
            {
                if (!Int64.TryParse(data, out n) || n < Math.Pow(10, 14))
                    return false;//数字验证
                if (m_address.IndexOf(data.Remove(2)) == -1)
                    return false;//省份验证

                string birth = data.Substring(6, 6).Insert(4, "-").Insert(2, "-");

                DateTime time;

                if (!DateTime.TryParse(birth, out time))
                    return false;//生日验证

                return true;//符合15位身份证标准
            }
            return false;
        }
        #endregion Temp

        //安全邮箱
        #region GetUserMail

        public void GetUserMailAsync(string code)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user == null || string.IsNullOrWhiteSpace(user.Value) ? code : user.Value;
            GetUserMailModel model = new GetUserMailModel
            {
                IdentityCode = current,
                IdentitySource = m_user_resource,
                Source = Request.UserHostAddress
            };
            ViewData["code"] = current;
            InitModel(model);
        }

        public ActionResult GetUserMailCompleted(UserMailEntry entry,string error) {
            ViewData["error"] = error;
            return View(entry);
        }

        #endregion GetUserMail

        //防沉迷
        #region ContainsUser

        public void ContainsUserAsync(string code) {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user == null || string.IsNullOrWhiteSpace(user.Value) ? code : user.Value;
            ContainsUserModel model = new ContainsUserModel {
                IdentityCode = current,
                Source = Request.UserHostAddress
            };
            ViewData["code"] = current;
            InitModel(model);
        }

        public ActionResult ContainsUserCompleted(bool entry,string error) {
            ViewData["contains"] = entry;
            ViewData["error"] = error;
            return View(entry);
        }

        #endregion ContainsUser

        //添加邮箱
        #region addemail
        public void AddEmailAsync(string code,string mail,string verifyvalue)
        {
            if (string.IsNullOrWhiteSpace(mail) || !m_email.IsMatch(mail))
            {
                return;
            }
            HttpCookie verifycode = Request.Cookies[m_resource];
            NewUserMailModel model = new NewUserMailModel
            {
                IdentityCode = code,
                UserMailAddress = mail,
                VerifyCode = verifycode != null ? verifycode.Value : null,
                VerifyValue = verifyvalue,
                Source = Request.UserHostAddress
            };

            InitModel(model);
        }
        public ActionResult AddEmailCompleted(UserMailEntry entry,string error)
        {
            return Json(entry != null ? entry.code : error);
        }

        #endregion addemail

        //添加身份证
        #region addidcard

        public void AddIdcardAsync(string code,string card,string username,string verifyvalue)
        {
            if (string.IsNullOrWhiteSpace(card) || string.IsNullOrWhiteSpace(username) || !IsIDCard(card) || !m_name.IsMatch(username))
            {
                return;
            }

            HttpCookie verifycode = Request.Cookies[m_resource];
            NewUserModel model = new NewUserModel
            {
                IdentityCode = code,
                UserCardID = card,
                VerifyCode = verifycode != null ? verifycode.Value : null,
                VerifyValue = verifyvalue,
                UserName = username,
                Source = Request.UserHostAddress
            };

            InitModel(model);
        }
        public ActionResult AddIdcardCompleted(string error)
        {
            return Json(error);
        }

        #endregion addidcard

        #region Validate

        public void ValidateAsync(string code)
        {
            ValidateUserModel model = new ValidateUserModel
            {
                UserCode = code,
                Old = m_old
            };
            InitModel(model);
        }

        public ActionResult ValidateCompleted(int entry)
        {
            return Content(entry.ToString());
        }

        #endregion Validate

    }
}
